import urllib

import asyncio
import requests
import json
import datetime
import sys

# url = 'http://127.0.0.1:10000/jypay/business_settled'
import requests
import time
import aes
import base64
import hashlib
import traceback
import aiohttp
import qrcode_terminal

def pay_core(url, data_obj):
    data = json.dumps(data_obj)
    cipher = aes.AesEncryption(aeskey)
    data = cipher.encrypt(data)
    data = base64.urlsafe_b64encode(data).decode('utf-8')
    request_obj = {
        'merchantid': merchantid,
        'data': data,
        'timestamp': str(int(time.time()))
    }
    sign_string = secretkey + merchantid + data + request_obj['timestamp'] + secretkey
    sign = hashlib.sha256(sign_string.encode("utf-8")).hexdigest()
    request_obj['sign'] = sign
    body = urllib.parse.urlencode(request_obj)
    print(body)
    response = requests.post(url, data=request_obj, timeout=61*3)
    print(response.content)
    rsp_data = json.loads(response.content.decode('utf-8'))

    if rsp_data['message'] != 'success':
        print(json.loads(response.content.decode()))
        return
    rsp_sign_string = secretkey + rsp_data['merchantid'] + rsp_data['data'] + rsp_data['timestamp'] + secretkey
    rsp_sign = hashlib.sha256(rsp_sign_string.encode('utf-8')).hexdigest()
    if rsp_sign != rsp_data['sign']:
        print("sign error")
    data = base64.urlsafe_b64decode(rsp_data['data'].encode('utf-8'))
    result = cipher.decrypt(data)
    print(json.loads(result))
    result = json.loads(result)
    if result.get("wx_url"):
        print(result.get("wx_url"))
        qrcode_terminal.draw(result.get("wx_url"))

async def hello(url, data_obj):
    begin = time.time()
    data = json.dumps(data_obj)
    cipher = aes.AesEncryption(aeskey)
    data = cipher.encrypt(data)
    data = base64.urlsafe_b64encode(data).decode('utf-8')
    request_obj = {
        'merchantid': merchantid,
        'data': data,
        'timestamp': str(int(time.time()))
    }
    sign_string = secretkey + merchantid + data + request_obj['timestamp'] + secretkey
    sign = hashlib.sha256(sign_string.encode("utf-8")).hexdigest()
    request_obj['sign'] = sign
    body = urllib.parse.urlencode(request_obj)
    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(url, data=request_obj) as resp:
                print(resp.status)
                if resp.status != 200:
                    print(resp.status)
                body = await resp.text()

                rsp_data = json.loads(body)

                if rsp_data['message'] != 'success':
                    print(body)
                    return
                rsp_sign_string = secretkey + rsp_data['merchantid'] + rsp_data['data'] + rsp_data[
                    'timestamp'] + secretkey
                rsp_sign = hashlib.sha256(rsp_sign_string.encode('utf-8')).hexdigest()
                if rsp_sign != rsp_data['sign']:
                    print("sign error")
                data = base64.urlsafe_b64decode(rsp_data['data'].encode('utf-8'))
                result = cipher.decrypt(data)
                print(json.loads(result))
                result = json.loads(result)
                if result.get("wx_url"):
                    print(result.get("wx_url"))
                    qrcode_terminal.draw(result.get("wx_url"))

        except:
            traceback.print_exc()
        print(time.time()- begin)

order_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if __name__ == '__main__':
    merchantid = "M2018072714131532672011"
    secretkey = "NDGZBSXRVOL1W5V74XSASMJKE62P7UW7"
    aeskey = "LSX2F3TCR0BEM4B7"

    if sys.argv[1] == 'cmcc':
        url = 'http://127.0.0.1:10040/pay/un_recharge'
        tasks = []
        for i in range(1):
            data_obj = {
                "ordernumber":  "R" + str(int(time.time())) + str(i),
                # "ordernumber": "R15402840860",
                "tel_number": "18503358520",
                "amount": "10",
                "backurl": "https://chanpay.8bill.cn/testnotify",
            }
            tasks.append(hello(url, data_obj))
    elif sys.argv[1] == 'ju':
        url = 'http://127.0.0.1:19901/pay/yk_recharge'
        tasks = []
        for i in range(1):
            data_obj = {
                "ordernumber":  "R" + str(int(time.time())) + str(i),
                # "ordernumber": "R15402840860",
                "cardno": "1000114400022752371",
                "tel_number": "13600452218",
                "amount": "200",
                "backurl": "https://chanpay.8bill.cn/testnotify",
            }
            tasks.append(hello(url, data_obj))
    elif sys.argv[1] == 'juc':
        url = 'http://127.0.0.1:19901/pay/yk_wxqrcode'
        tasks = []
        for i in range(1):
            data_obj = {
                "payorderno": "test" + str(int(time.time())) + str(i),
                "amount": "20",
                "backurl": "https://chanpay.8bill.cn/testnotify",
            }
            tasks.append(hello(url, data_obj))
    elif sys.argv[1] == 'test':
        url = 'http://127.0.0.1:9900/pay/recharge'
        while True:
            data_obj = {
                "ordernumber": "R" + str(int(time.time())),
                "tel_number": "17606096618",
                "amount": "10",
                "backurl": "https://chanpay.8bill.cn/testnotify",
            }
            pay_core(url, data_obj)
            time.sleep(60)
    elif sys.argv[1] == 'testuc':
        url = 'http://127.0.0.1:9900/pay/wxqrcode'
        while True:
            data_obj = {
                "payorderno": "P" + str(int(time.time())),
                "amount": "10"
            }

            time.sleep(2*60*60)
            pay_core(url, data_obj)
    elif sys.argv[1] == 'uc':
        url = 'http://127.0.0.1:10040/pay/un_wxqrcode'
        tasks = []
        for i in range(1):
            data_obj = {
                "payorderno": "test" + str(int(time.time())) + str(i),
                "amount": "10",
                "backurl": "https://chanpay.8bill.cn/testnotify",
                "ip": "113.67.227.7",
		"pay_channel": "WXH5"
            }
            tasks.append(hello(url, data_obj))
    elif sys.argv[1] == 'cq':

        url = 'http://127.0.0.1:10040/pay/un_query'
        tasks = []
        for i in range(1):
            data_obj = {
                "ordernumber": sys.argv[2]
                # "payorderno": sys.argv[2],
            }
            tasks.append(hello(url, data_obj))
    elif sys.argv[1] == 'rq':

        url = 'http://127.0.0.1:19901/pay/yk_query'
        tasks = []
        for i in range(1):
            data_obj = {
                "ordernumber": sys.argv[2]
                # "payorderno": sys.argv[2],
            }
            tasks.append(hello(url, data_obj))
    elif sys.argv[1] == 're':

        url = 'http://127.0.0.1:19901/pay/refresh'
        tasks = []
        for i in range(1):
            data_obj = {
                "ordernumber": sys.argv[2]
                # "payorderno": sys.argv[2],
            }
            tasks.append(hello(url, data_obj))
    elif sys.argv[1] == 'queue':
        url = 'http://hh.91link.link:8090/pay/order_total'
        tasks = []
        for i in range(1):
            data_obj = {

            }
            tasks.append(hello(url, data_obj))

    print(json.dumps(data_obj))

    # c = input("confirm c contune ,e exit")
    # if c != 'c':
    #     exit()
    # print(time.time())
    # pay_core(url, data_obj)
    # print(time.time())
    loop = asyncio.get_event_loop()
    now = time.time()
    loop.run_until_complete(asyncio.wait(tasks))
    print(time.time() - now)
    loop.close()
